﻿using B.MESUI.Login.EquipmentManagement.DTO;
using B.MESUI.Login.EquipmentManagement.Model;
using DevExpress.XtraEditors;
using Newtonsoft.Json;
using Newtonsoft.Json.Bson;
using Standard;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static DevExpress.Drawing.Printing.Internal.DXPageSizeInfo;

namespace B.MESUI.Login.EquipmentManagement.DeviceLedgerService
{
    public partial class ShowDeviceLedgerForm : DevExpress.XtraEditors.XtraForm
    {
        private readonly DeviceGridPanel devicePanel;
        public ShowDeviceLedgerForm()
        {
            InitializeComponent();
            // 1. 创建控件实例
            devicePanel = new DeviceGridPanel();
            devicePanel.Dock = DockStyle.Fill;

            // 2. 加入到主窗体的某个Panel或直接加到this.Controls
            this.Controls.Add(devicePanel);

            // 3. 生成动态查询控件（如果没有查询就可以直接隐藏了）
            GenerateDeviceSearchControls();

            // 4. 绑定事件
            devicePanel.AddClicked += (s, e) => { /* 新增逻辑 */
                AddDeviceLedger Add = new AddDeviceLedger();
                Add.ShowDialog();
                if (Add.DialogResult == DialogResult.OK) 
                {
                    FlushData();
                }
            };
            devicePanel.ExportClicked += async(s, e) => { /* 导出逻辑 */

                using (SaveFileDialog saveFileDialog = new SaveFileDialog())
                {
                    saveFileDialog.Title = "请选择导出文件保存位置";
                    saveFileDialog.Filter = "Excel文件|*.xls|所有文件|*.*";
                    saveFileDialog.FileName = "设备台账列表.xls";

                    if (saveFileDialog.ShowDialog() == DialogResult.OK)
                    {
                        try
                        {
                            using (HttpClient client = new HttpClient())
                            {
                                string url = $"{BaseUrl.Url}DeviceLedger/ExportDeviceLedgera"; // 你的后端接口地址
                                var response = await client.GetAsync(url);
                                response.EnsureSuccessStatusCode();

                                using (var stream = await response.Content.ReadAsStreamAsync())
                                using (var fileStream = new FileStream(saveFileDialog.FileName, FileMode.Create, FileAccess.Write))
                                {
                                    await stream.CopyToAsync(fileStream);
                                }
                            }
                            MessageBox.Show("导出成功！");
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show("导出失败：" + ex.Message);
                        }
                    }
                }

            };
            devicePanel.DeleteClicked += async (s, e) =>
            {
                /* 删除逻辑 */
                var ids = devicePanel.GetSelectedIdsString();
                
                if(ids.Length == 0) {  MessageBox.Show("请选择要删除的数据！！！"); }
                else 
                {
                    using (HttpClient client = new HttpClient()) 
                    {
                        var url = $"{BaseUrl.Url}DeviceLedger/Delete?id={ids}";
                        var response = await client.DeleteAsync(url);
                        response.EnsureSuccessStatusCode();
                        var json = await response.Content.ReadAsStringAsync();
                        var result = JsonConvert.DeserializeObject<ApiResult<int>>(json);
                        MessageBox.Show(result.Message);
                        FlushData();
                    }
                }
            };
            //编辑事件
            devicePanel.EditClicked += (s, e) => { 
                AddDeviceLedger Updaate=new AddDeviceLedger(e);
                Updaate.ShowDialog();
                if (Updaate.DialogResult == DialogResult.OK) 
                {
                    FlushData();
                }
            };

            // 查询事件
            devicePanel.SearchClicked += async (s, e) =>
            {
                // 获取查询条件
                var searchConditions = devicePanel.GetSearchConditions();
                // 重置到第一页进行查询
                var result = await GetDeviceTypeListAsync(1, devicePanel.PageSize, searchConditions);
                BindDataSetColumns(result.Data);
                devicePanel.SetPageInfo(1, devicePanel.PageSize, result.TotalCount);
            };
            // 重置事件
            devicePanel.ResetClicked += async (s, e) =>
            {
                // 重置查询条件
                devicePanel.ResetSearchConditions();
                // 重新加载第一页数据
                var result = await GetDeviceTypeListAsync(1, devicePanel.PageSize);
                BindDataSetColumns(result.Data);
                devicePanel.SetPageInfo(1, devicePanel.PageSize, result.TotalCount);
            };

            // 5. 分页事件
            devicePanel.OnPageChanged += async (pageIndex, pageSize) =>
            {
                // 获取当前查询条件
                var searchConditions = devicePanel.GetSearchConditions();
                // 这里调用你的后端API
                var result = await GetDeviceTypeListAsync(pageIndex, pageSize, searchConditions); // 你的API
                BindDataSetColumns(result.Data);
                devicePanel.SetPageInfo(pageIndex, pageSize, result.TotalCount);
            };
        }
        //添加查询控件方法
        private void GenerateDeviceSearchControls()
        {
            // 字段名和控件类型的映射（后端定义）
            var fieldMappings = new Dictionary<string, SearchControlType>
            {
                /*支持的控件类型：
               - SearchControlType.TextBox: 文本框
               - SearchControlType.ComboBox: 下拉框
               - SearchControlType.DateEdit: 日期选择器
               - SearchControlType.CheckBox: 复选框*/
                //示例前面查询的字段名，后面是控件类型：{ "Name", SearchControlType.TextBox },
                { "AssetNumber", SearchControlType.TextBox },
                { "Code", SearchControlType.TextBox },
                { "Name", SearchControlType.TextBox },
                { "State", SearchControlType.ComboBox }
            };

            // 显示名称映射（可选）
            var displayNames = new Dictionary<string, string>
            {
                //也就是修改查询显示的名称{ "Name", "设备名称" },
                { "AssetNumber", "设备序列号" },
                { "Code","编码" },
                { "Name", "名称" },
                { "State", "状态" }
            };

            // 下拉框选项（可选）
            var comboOptions = new Dictionary<string, List<string>>
            {
                //你的下拉里面的内容，左侧选择一个你添加的下拉名，手动就直接写，动态的就直接直接抓取给值就行了{ "State", new List<string> { "正常", "维修中", "报废", "闲置" } }
                { "State", new List<string> {"正常","维修中","报废","闲置" } }
            };
            //调用动态生成查询控件方法
            devicePanel.GenerateSearchControls(fieldMappings, displayNames, comboOptions);
        }

        /// <summary>
        /// 绑定数据、隐藏指定列、设置列名方法
        /// </summary>
        private void BindDataSetColumns(List<DeviceLedger> data)
        {
            // 需要隐藏的列名
            var hideColumnNames = new[] { "IsDeleted","Id" ,"One","UpdateUserName"};

            // 列名映射
            var columnCaptions = new Dictionary<string, string>
            {
                { "AssetNumber", "设备序列号" },
                { "Code", "编码" },
                { "Name", "设备名称" },
                { "TypeId", "类型" },
                { "State", "状态" },
                { "Specification", "规格" },
                { "Model", "型号" },
                { "Brand", "品牌" },
                { "Num", "数量" },
                { "DateOfManufacture", "生产日期" },
                { "EntryDateToTheFactory", "入厂日期" },
                { "SupplierId", "供应商" },
                { "WorkShopId", "所属车间" },
                { "Location", "位置" },
                { "DepartmentId", "使用部门" },
                { "PersonInChargeId", "责任人" },
                { "Remark", "备注" },
                { "CreatedUserName", "创建人" },
                { "CreatedTime", "创建时间" },
                { "UpdateTime", "更新时间" },
                // 其他字段...
            };

            devicePanel.SetDataSource(data);
            foreach (var colName in hideColumnNames)
            {
                var col = devicePanel.gridView.Columns[colName];
                if (col != null)
                    col.Visible = false;
            }
            devicePanel.SetColumnCaptions(columnCaptions);
        }

        // 获取显示值方法伪代码，实际根据你的后端API来写
        private async Task<(List<DeviceLedger> Data, int TotalCount)> GetDeviceTypeListAsync(int pageIndex, int pageSize, Dictionary<string, object> searchConditions = null)
        {
            // 调用后端接口，返回数据和总数
            using (var client = new HttpClient())
            {
                // 构建查询参数
                var queryParams = new List<string>
                {
                    $"PageIndex={pageIndex}",
                    $"PageSize={pageSize}"
                };

                // 添加查询条件
                if (searchConditions != null && searchConditions.Count > 0)
                {
                    foreach (var condition in searchConditions)
                    {
                        if (condition.Value != null)
                        {
                            string value = condition.Value.ToString();
                            if (!string.IsNullOrEmpty(value))
                            {
                                // 根据值类型进行不同的处理
                                if (condition.Value is DateTime dateTime)
                                {
                                    value = dateTime.ToString("yyyy-MM-dd");
                                }
                                else if (condition.Value is bool boolValue)
                                {
                                    value = boolValue.ToString().ToLower();
                                }

                                queryParams.Add($"{condition.Key}={Uri.EscapeDataString(value)}");
                            }
                        }
                    }
                }

                string queryString = string.Join("&", queryParams);
                //改成自己的接口
                string url = $"{BaseUrl.Url}DeviceLedger/GetList?{queryString}";
                //替换为自己的传值方式"Get","Post","Put","Delete"
                var response = await client.GetAsync(url);
                response.EnsureSuccessStatusCode();
                var json = await response.Content.ReadAsStringAsync();
                //替换为你自己的数据模型
                var result = JsonConvert.DeserializeObject<ApiPaging<DeviceLedger>>(json);
                return (result.PageDatas, result.TotalCount);
            }
        }

        private  void ShowDeviceLedgerForm_Load(object sender, EventArgs e)
        {
            FlushData();
        }
        /// <summary>
        /// 刷新数据
        /// </summary>
        private async void FlushData()
        {
            // 首次加载第一页
            var result = await GetDeviceTypeListAsync(1, 20);//默认1页20条
            BindDataSetColumns(result.Data);
            devicePanel.SetPageInfo(1, 20, result.TotalCount);
        }

    }

}
